package com.briup.run.util;

//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/9/19-09-19-15:42
 * @Description: 生成验证码图片
 */
public class ImageUtil {
    public static void createAuthImg(HttpServletRequest req, HttpServletResponse resp) {
        try {
            int width = 60;
            int height = 20;

            //创建一对象,在内存中图片（验证码图片对象）
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            //填充背景色
            Graphics g = bufferedImage.getGraphics();   //画笔对象
            g.setColor(Color.pink); //画笔颜色
            g.fillRect(0, 0, width, height);

            //画边框
            g.setColor(Color.blue);
            g.drawRect(0, 0, width - 1, height - 1);

            String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
            //生成随机角标
            Random ran = new Random();
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= 4; i++) {
                int index = ran.nextInt(str.length());
                //获取字符
                char c = str.charAt(index);
                sb.append(c);
                Font font = new Font("Verdana", Font.PLAIN, 15);
                g.setFont(font);
                g.drawString(c + "", width / 5 * i, 16);
            }
            String checkCode_session = sb.toString();
            // 存session
            req.getSession().setAttribute("authCode", checkCode_session);

            //画干扰线
            g.setColor(Color.green);

            //随机生成坐标点
            for (int i = 0; i < 5; i++) {
                int x1 = ran.nextInt(width);
                int x2 = ran.nextInt(12);
                int y1 = ran.nextInt(height);
                int y2 = ran.nextInt(12);
                g.drawLine(x1, y1, x2, y2);
            }

            //将图片输出到页面展示
            ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
